<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>js字符串之替换操作</title>
</head>
<body>
  <p>字符串之替换操作</p>
  <ul>
    <li>字符串替换使用replace,可传入字符串或者正则表达式,但只替换第一个满足条件的字符串</li>
    <li>可以使用正则来扩展replaceAll,替换所有满足条件的字符串</li>
  </ul>
  <div id="template"></div>
  <script>
    const name = 'Miracle'
    console.log(name.replace('Miracle', 'Miracle He'))
    const web = 'https://github.com/miracle-github/fts/js'
    console.log(web.replace(/github/g, 'cnblogs'))
    // 扩展replaceAll
    String.prototype.replaceAll = function (s1, s2) {
      return this.replace(new RegExp(s1, 'gm'), s2)
    }
    console.log(web.replaceAll('github', 'cnblogs'))
    const skills = ['js', 'es', 'ts']
    const html = `${name} is learning ${skills.join(', ')}`
    const result = skills.reduce((res, item) => res.replace(item, `<a href="?s=${item}">${item}</a>`), html)
    document.getElementById('template').innerHTML = result
  </script>
</body>
</html>